package com.guoxin.concurrentprogramming.chapter2;

public class StopThreadUnsaft {
    private static final User USER = new User();

    private static class User{
        private int id=0;
        private String name="0";

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    private static class ChangeObjectThread extends Thread {

        @Override
        public void run() {
            while(true){
                synchronized (USER){
                    int v = (int) (System.currentTimeMillis()/1000);
                    USER.setId(v);
                    try {
                        Thread.sleep(100 );
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    USER.setName(String.valueOf(v));
                }
            }
        }
    }

    private static class ReadObjectThread extends Thread {
        @Override
        public void run() {
            while (true){
                synchronized (USER){
                    if(USER.getId()!=Integer.parseInt(USER.getName())){
                        System.out.println(USER);
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ReadObjectThread().start();

        while (true){
            Thread t = new ChangeObjectThread();
            t.start();
            Thread.sleep(100);
            t.stop();
        }
    }
}
